package com.sibrary.booxoo;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;

public class BooxooBookmarksAddActivity extends Activity {

	private String mTitle;
	private String mUrl;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Window w = getWindow();
		w.requestFeature(Window.FEATURE_LEFT_ICON);

		setContentView(R.layout.booxoo_bookmarks_add_activity);
		setTitle(R.string.title_activity_booxoo_add_bookmarks);

		Intent intent = getIntent();
		mTitle = intent.getStringExtra("bookmarksTitle");
		mUrl = intent.getStringExtra("bookmarksUrl");
		fillDataToEdit();

		Button okBtn = (Button) findViewById(R.id.BookmarksActivity_bookmarksBtnOk);
		okBtn.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				addOneBookmark(mTitle, mUrl);
				
				Intent intent = new Intent();
				setResult(BooxooMainActivity.BOOKMARKS_ADD_REQUEST_CODE, intent);
				finish();
			}
		});

		Button cancelBtn = (Button) findViewById(R.id.BookmarksActivity_bookmarksBtnCancel);
		cancelBtn.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();
			}
		});
	}

	/**
	 * 填充数据
	 */
	private void fillDataToEdit() {
		EditText titleEditText = (EditText) findViewById(R.id.BookmarksAddActivity_bookmarksTitleEditText);
		EditText urlEditText = (EditText) findViewById(R.id.BookmarksActivity_bookmarksUrlEditText);

		titleEditText.setText(mTitle);
		urlEditText.setText(mUrl);
	}

	/**
	 * 添加书签
	 * 
	 * @param title
	 * @param url
	 */
	private void addOneBookmark(String title, String url) {

		ContentValues inputValue = new ContentValues();
		inputValue.put(android.provider.Browser.BookmarkColumns.BOOKMARK, 1); // Bookmark值为1
		inputValue.put(android.provider.Browser.BookmarkColumns.TITLE, title);
		inputValue.put(android.provider.Browser.BookmarkColumns.URL, url);
		ContentResolver cr = getContentResolver();

		cr.insert(android.provider.Browser.BOOKMARKS_URI, inputValue); // 向浏览器添加该书签
	}
}
